<template>
  <div class="create-course-container">
    <el-page-header @back="goBack" content="创建课程" />
    
    <el-card class="form-card">
      <el-form 
        ref="formRef" 
        :model="form" 
        :rules="rules" 
        label-position="top"
      >
        <el-form-item label="课程名称" prop="couName">
          <el-input 
            v-model="form.couName" 
            placeholder="请输入课程名称" 
            clearable 
          />
        </el-form-item>
        
        <el-form-item label="课程简介">
          <el-input
            v-model="form.couIntroduction"
            type="textarea"
            :rows="4"
            placeholder="请输入课程简介"
            maxlength="255"
            show-word-limit
          />
        </el-form-item>
        
        <el-form-item label="课程封面">
          <el-upload
            class="avatar-uploader"
            action="/api/upload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="form.couPic" :src="form.couPic" class="avatar">
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        
        <el-form-item label="课程价格">
          <el-input-number 
            v-model="form.couPrice" 
            :min="0" 
            :precision="2" 
            :step="10"
            placeholder="请输入课程价格"
          />
          <span class="price-unit">元</span>
        </el-form-item>
        
        <el-form-item label="课程章节">
          <div class="chapters-container">
            <div 
              v-for="(chapter, index) in form.chapters" 
              :key="index" 
              class="chapter-item"
            >
              <el-form-item 
                :prop="'chapters.' + index + '.title'" 
                :rules="chapterRules.title"
                style="margin-right: 10px;"
              >
                <el-input
                  v-model="chapter.title"
                  placeholder="章节名称"
                  style="width: 200px;"
                />
              </el-form-item>
              
              <el-form-item 
                :prop="'chapters.' + index + '.url'" 
                :rules="chapterRules.url"
                style="margin-right: 10px;"
              >
                <el-input
                  v-model="chapter.url"
                  placeholder="章节链接(可选)"
                  style="width: 300px;"
                  @blur="validateUrl(chapter)"
                />
              </el-form-item>
              
              <el-button
                type="danger"
                plain
                size="small"
                @click="removeChapter(index)"
              >
                删除
              </el-button>
            </div>
            <el-button 
              type="primary" 
              plain 
              @click="addChapter"
              style="margin-top: 10px;"
            >
              添加章节
            </el-button>
          </div>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="submitForm">提交</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { teacherApi } from '@/api/teacher'
import { useAuthStore } from '@/stores/auth'

const router = useRouter()
const authStore = useAuthStore()
const teacherId = ref(null)

const formRef = ref()
const form = reactive({
  couName: '',
  couIntroduction: '',
  couPic: '',
  couPrice: 0,
  chapters: [] // 初始为空数组
})

// URL验证正则表达式
const urlPattern = /^(http?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/

const rules = {
  couName: [
    { required: true, message: '请输入课程名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ]
}

const chapterRules = {
  title: [
    { required: true, message: '请输入章节名称', trigger: 'blur' },
    { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  url: [
    {
      validator: (rule, value, callback) => {
        if (!value || value.trim() === '') {
          callback()
        } else if (!urlPattern.test(value)) {
          callback(new Error('请输入有效的URL链接'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 返回上一页
const goBack = () => {
  router.go(-1)
}

// 添加章节
const addChapter = () => {
  form.chapters.push({ 
    title: '', 
    url: '', 
    index: form.chapters.length + 1 
  })
}

// 删除章节
const removeChapter = (index) => {
  form.chapters.splice(index, 1)
  // 重新计算章节索引
  form.chapters.forEach((chapter, idx) => {
    chapter.index = idx + 1
  })
}

// 手动验证URL
const validateUrl = (chapter) => {
  if (chapter.url && chapter.url.trim() !== '' && !urlPattern.test(chapter.url)) {
    ElMessage.warning('请输入有效的URL链接')
  }
}

// 图片上传成功
const handleAvatarSuccess = (response) => {
  form.couPic = response.data.url
}

// 图片上传前校验
const beforeAvatarUpload = (file) => {
  const isJPGorPNG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPGorPNG) {
    ElMessage.error('上传头像图片只能是 JPG/PNG 格式!')
  }
  if (!isLt2M) {
    ElMessage.error('上传头像图片大小不能超过 2MB!')
  }
  return isJPGorPNG && isLt2M
}

// 获取教师ID
const fetchTeacherId = async () => {
  try {
    if (!authStore.userId) {
      throw new Error('用户ID不存在')
    }

    const response = await teacherApi.getTeacherByUid(authStore.userId)
    const teacherData = response.data || response
    
    if (!teacherData) {
      throw new Error('教师信息不存在')
    }
    
    if (!teacherData.id) {
      throw new Error('教师ID不存在')
    }
    
    teacherId.value = teacherData.id
    return teacherId.value
  } catch (error) {
    ElMessage.error('获取教师信息失败: ' + error.message)
    return null
  }
}

// 提交表单
const submitForm = async () => {
  try {
    await formRef.value.validate()
    
    // 获取教师ID（保持不变）
    const tid = await fetchTeacherId()
    if (!tid) {
      return
    }
    
    // 过滤空章节（保持不变）
    const validChapters = form.chapters
      .filter(chapter => chapter.title && chapter.title.trim())
      .map((chapter, index) => ({
        title: chapter.title,
        url: chapter.url || null,
        index: index + 1
      }))
    
    // 验证URL（保持不变）
    const hasInvalidUrl = validChapters.some(chapter => chapter.url && !urlPattern.test(chapter.url))
    if (hasInvalidUrl) {
      ElMessage.warning('请检查章节链接格式')
      return
    }
    
    // 构建课程数据（保持不变）
    const courseData = {
      teaId: tid,
      couName: form.couName,
      couIntroduction: form.couIntroduction || null,
      couPic: form.couPic || null,
      couPrice: form.couPrice || 0,
      chapters: validChapters.length > 0 ? validChapters : null
    }
    
    console.log('准备提交的数据:', JSON.stringify(courseData, null, 2))
    
    const response = await teacherApi.createCourseWithChapters(courseData)
    console.log('API响应:', response)
    
    // 修改判断条件：直接检查response是否存在id字段
    if (response?.id) {  // 或者 response && 'id' in response
      ElMessage.success('课程创建成功')
      router.push('/teacher/courses')
    } else {
      throw new Error(`API返回数据格式异常: ${JSON.stringify(response)}`)
    }
  } catch (error) {
    console.error('完整错误信息:', error)
    ElMessage.error(`创建课程失败: ${error.message}`)
  }
}

// 重置表单
const resetForm = () => {
  formRef.value.resetFields()
  form.couName = ''
  form.couIntroduction = ''
  form.couPic = ''
  form.couPrice = 0
  form.chapters = []
}
</script>

<style scoped>
.create-course-container {
  padding: 20px;
  max-width: 1000px;
  margin: 0 auto;
}

.form-card {
  margin-top: 20px;
}

.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 178px;
  height: 178px;
}

.avatar-uploader:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.price-unit {
  margin-left: 10px;
  color: #666;
}

.chapters-container {
  border: 1px solid #eee;
  padding: 15px;
  border-radius: 4px;
}

.chapter-item {
  display: flex;
  align-items: flex-start;
  margin-bottom: 10px;
  flex-wrap: wrap;
  gap: 10px;
}

.chapter-item .el-form-item {
  margin-bottom: 0;
}
</style>